<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
</head>
<body>
<div id="app">
    <h1>A login: {{ $store.state.a.login }}</h1>
    <h1>B click: {{ $store.state.b.clicks }}</h1>
    <h1>Root click: {{ $store.state.clicks }}</h1>
    <button @click="loginA">A login</button>
    <button @click="addB">B click+</button>
    <button @click="addR">Root click+</button>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.5.1/dist/vuex.js"></script>
<script>
    // 一些大型的应用上，状态可能很多，如果全部有一个store管理，容易导致臃肿，
    // 因此vuex支持模块化， 模块化store支持树状多层级，下面演示两层级
    const moduleA = {
        state: {
            login: false
        },
        mutations: {
            setLogin(state, login) {
                state.login = login
            }
        },
        getters: {
            isLogin: state => {
                return state.login;
            }
        }
    };
    const moduleB = {
        state: {
            clicks: 0
        },
        mutations: {
            add(state, n=1) {
                state.clicks += n;
            },
        },
        getters: {
            // rootState是根模块的state
            count: (state, rootState) => {
                console.log('count => ', state.clicks, rootState.clicks);
                return state.clicks;
            }
        },
        actions: {
            addRoot({state, commit, rootState}) {
                console.log('addRoot => ', state.clicks, rootState.clicks);
                // 不但会触发本模块的add方法，其他模块或者根模块的add也会被触发
                commit('add', rootState.clicks);
            }
        }
    };

    const store = new Vuex.Store({
        state: {
            clicks: 10
        },
        mutations: {
            add(state) {
                state.clicks ++;
            }
        },
        modules: {
            a: moduleA,
            b: moduleB
        }
    });

    let vm = new Vue({
        el: "#app",
        data: {
            count: 0,
            login: false
        },
        methods: {
            loginA() {
                // 触发moduleA的setLogin修改方法
                this.$store.commit('setLogin', this.login = !this.login);
            },
            addB() {
                this.$store.dispatch('addRoot');
            },
            addR() {
                // root的store方法add会触发，moduleB的也会被触发
                // 说明只要mutation名字相同的不论是子模块还是根模块都会被触发
                this.$store.commit('add');
            }
        },
        store
    });
</script>
</body>
</html>
